package tranc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

import util.DBPoolUtils;

public class TrancDemo {

	@Test
	public void test() throws SQLException {
		// 1.得到连接
		Connection c = DBPoolUtils.getConnection();
		// 2.关闭自动提交
		c.setAutoCommit(false);
		
		// 3.得到句柄
		Statement s = c.createStatement();
		int row = s.executeUpdate("update menu set price=price-10 where id=1 and price >= 10");
		int row2 = s.executeUpdate("update menu set price=price+10 where id=2");
		
		// 4.判断是否都成功
		if (row == 1 && row2 == 1) {
			// 5.提交事务
			c.commit();
		}else {
			// 6.事务回滚
			c.rollback();
		}
		
		// 开启自动提交
		c.setAutoCommit(true);
		c.close();
	}
}
